package com.mdnote.structure.hashtable;

import org.omg.PortableInterceptor.USER_EXCEPTION;

import java.io.Serializable;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/8/28
 * @description 链表
 */
public class UserBucketLinkedList {


    private int bucketIndex;

    /**
     * 这里没有头元素，默认就是第一个元素了
     */
    private User head;

    public UserBucketLinkedList(int bucketIndex) {
        this.bucketIndex = bucketIndex;
    }

    public void addByOrder(User user) {
        // 看看是不是没有元素
        if (head == null) {
            head = user;
            return;
        }
        // 遍历链表
        User temp = head;
        while (temp.getNext() != null && user.getId() >= temp.getNext().getId()) {
            temp = temp.getNext();
        }
        if (temp.getNext() != null) {
            user.setNext(temp.getNext());
        }
        temp.setNext(user);
    }

    public void remove(Serializable id) {
        if (head == null) {
            System.out.println("没有钙元素");
            return;
        }
        if (head.getId() == id) {
            head = null;
            return;
        }
        User temp = head;
        while (temp.getNext() != null && temp.getNext().getId() != id) {
            temp = temp.getNext();
        }
        if (temp.getNext() == null) {
            // 没找到
            System.out.println("找不到钙元素");
        } else {
            // 找到了
            temp.setNext(temp.getNext().getNext());
        }
    }

    public void list() {
        if (head == null) {
            System.out.println("链表为空");
            return;
        }
        System.out.println("Bucket " + this.bucketIndex + ":");
        User temp = head;
        while (temp != null) {
            System.out.printf("=> id = %d. name = %s", temp.getId(), temp.getUsername());
            temp = temp.getNext();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        UserBucketLinkedList userBucketLinkedList = new UserBucketLinkedList(0);
        userBucketLinkedList.addByOrder(new User(11L, "AAA", "123"));
        userBucketLinkedList.addByOrder(new User(22L, "AAA", "123"));
        userBucketLinkedList.addByOrder(new User(33L, "AAA", "123"));

        userBucketLinkedList.remove(22L);
        userBucketLinkedList.list();
    }
}
